/* 
 *  h264文件解码yuv测试
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include "ffmpeg_codec.h"

int main(int argc, char **argv)
{
    int ret;
    int fd;
    void *handle = NULL;
    FFCodec_Map yuvMap[3];
    uint32_t frameCount = 0;

    //读文件缓冲区
    uint8_t *pBuff;
    uint8_t *buff;
    uint32_t buffSize;

    //截取h264帧数据用
    int32_t buffLen = 0;
    int32_t buffOffset = 0;
    int32_t frameSize = 0;
    char type = 0;

    if (argc < 2 || strstr(argv[1], "help") || strstr(argv[1], "?"))
    {
        printf("\r\n"
            "Usage: %s [h264 file]\r\n"
            "Example: %s ./640x480_30fps.h264\r\n",
            argv[0], argv[0]);
        return -1;
    }

    printf("\r\n--- %s start ---\r\n", argv[0]);

    //读h264文件
    fd = open(argv[1], O_RDONLY);
    if (fd < 1)
    {
        printf("open %s failed \r\n", argv[1]);
        return -1;
    }

    //编码器初始化
    handle = ffcodec_init(
        CODEC_TYPE_DECODE,
        CODEC_FORMAT_H264,
        CODEC_FORMAT_NONE,
        0,
        0,
        0,
        0,
        0);
    if (!handle)
    {
        printf("ffcodec_init: failed \r\n");
        close(fd);
        return -1;
    }

    //读文件缓冲区
    buffSize = 1024 * 1024;
    buff = (uint8_t*)calloc(buffSize, 1);

    //解100帧
    while (frameCount < 100)
    {
        //剩余缓冲区数据往前移动
        h26xMoveBuff(buff, &buffLen, &buffOffset, &frameSize);

        //读文件到缓冲区后面
        ret = read(fd, buff + buffLen, buffSize - buffLen);
        if (ret < buffSize - buffLen)
            lseek(fd, 0, SEEK_SET);
        buffLen += ret;

        //定位帧数据
        buffOffset = h26xFindFrame(buff, buffLen, &frameSize, &type);
        if (buffOffset < 0)
            continue;

        //待解码帧
        pBuff = buff + buffOffset;
        printf("input: len/%d - %02X %02X %02X %02X %02X ",
            frameSize, pBuff[0], pBuff[1], pBuff[2], pBuff[3], pBuff[4]);
        
        //解码
        ret = ffcodec_decode(handle, pBuff, frameSize, yuvMap, NULL);
        if (ret == 0)
        {
            printf("-- output: %dx%d - Y %02X %02X %02X - U %02X %02X %02X - V %02X %02X %02X - index %d",
                yuvMap[0].width, yuvMap[0].height,
                yuvMap[0].map[0], yuvMap[0].map[1], yuvMap[0].map[2],
                yuvMap[1].map[0], yuvMap[1].map[1], yuvMap[1].map[2],
                yuvMap[2].map[0], yuvMap[2].map[1], yuvMap[2].map[2],
                frameCount++);
        }
        printf("\r\n");
    }

    //释放
    free(buff);
    ffcodec_deinit(handle);
    close(fd);

    printf("\r\n--- %s end ---\r\n", argv[0]);
    return 0;
}
